/** @method ConditionGroup
 *  @description 条件组
 **/
import React, { useState, useEffect } from 'react';
import { Button } from 'antd';
import ConditionGroupItem from './ConditionGroupItem';
import { randomKey } from '../../utils/utils';
import './index.less';

export default function ConditionGroups(props) {
  const { logs } = props;

  const [conditionGroups, setConditionGroups] = useState([]);

  useEffect(() => {
    if (props.value.length > 0) {
      setConditionGroups(initData(props.value));
    } else {
      addGroup(true);
    }
  }, [props.value]);
  // console.log('xxxx', logs, conditionGroups);
  function initData(data) {
    const newData = data.map((item) => {
      item.id = item.id ? item.id : randomKey();
      item.conditions = item.conditions.map((item) => {
        item.id = item.id ? item.id : randomKey();
        return item;
      });
      return item;
    });
    return newData;
  }

  const handleChange = (id, value) => {
    for (let i = 0; i < conditionGroups.length; i++) {
      if (conditionGroups[i].id === id) {
        conditionGroups[i] = value;
      }
    }
    props.onChange && props.onChange(conditionGroups);
  };

  //添加组
  function addGroup(isFirst) {
    const group = {
      junction_type: isFirst ? 'none' : 'and',
      conditions: [
        {
          junction_type: 'none',
          id: randomKey(),
        },
      ],
      id: randomKey(),
    };
    if (isFirst) {
      setConditionGroups(Object.assign([], [group]));
      props.onChange && props.onChange([group]);
    } else {
      conditionGroups.push(group);
      setConditionGroups(Object.assign([], conditionGroups));
      props.onChange && props.onChange(conditionGroups);
    }
  }

  // 删除组
  const del = (index) => {
    conditionGroups.splice(index, 1);
    setConditionGroups(Object.assign([], conditionGroups));
    props.onChange && props.onChange(conditionGroups);
  };
  return (
    <div className='condition-group'>
      {conditionGroups.map((item, index) => {
        const _isHit = ((logs && logs.rules && logs.rules.find((it) => it.id === item.id)) || {}).hit;

        return (
          <div key={item.id}>
            <ConditionGroupItem
              {...props}
              placeholder={props.placeholder}
              variable={props.variable}
              using_variables={props.using_variables}
              value={item}
              isFirst={index === 0}
              onChange={handleChange.bind(this, item.id)}
              onDel={del.bind(this, index)}
              operatorOptions={props.operatorOptions}
              disabled={props.disabled}
              compareData={(props.compareData && props.compareData[index]) || undefined}
              isHit={_isHit}
            />
          </div>
        );
      })}

      <div className='condition-add-btn'>
        {!props.disabled && <Button onClick={() => addGroup()}>添加条件组</Button>}
      </div>
    </div>
  );
}
